package net.qhzw.vip.qiyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import net.qhzw.vip.qiyu.dto.CategoryDto;
import net.qhzw.vip.qiyu.entity.Category;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.CategoryService;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("prod/category")
@Api(tags = "分类管理")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private MapperFacade mapperFacade;


    /**
     * 分类信息列表接口
     */
    @GetMapping("/categoryInfo")
    @ApiOperation(value = "分类信息列表", notes = "获取所有的产品分类信息，顶级分类的parentId为0,默认为顶级分类")
    @ApiImplicitParam(name = "parentId", value = "分类ID", required = false, dataType = "Long")
    public JsonResult<List<CategoryDto>> categoryInfo(@RequestParam(value = "parentId", defaultValue = "0") Long parentId) {
        List<Category> categories = categoryService.listByParentId(parentId);
        List<CategoryDto> categoryDtos = mapperFacade.mapAsList(categories, CategoryDto.class);
        return JsonResult.ok(categoryDtos);
    }

    /**
     * 获取菜单页面的表
     *
     * @return
     */
    @GetMapping("/table")
    public JsonResult<List<Category>> table() {
        List<Category> categoryMenuList = categoryService.tableCategory(SecurityUtils.getLoginUser().getShopId());
        return JsonResult.ok(categoryMenuList);
    }

    /**
     * 获取分类信息
     */
    @GetMapping("/info/{categoryId}")
    public JsonResult<Category> info(@PathVariable("categoryId") Long categoryId) {
        Category category = categoryService.getById(categoryId);
        return JsonResult.ok(category);
    }


    /**
     * 保存分类
     */
    @PostMapping
    public JsonResult<Void> save(@RequestBody Category category) {
        category.setCategoryId(IdWorker.getId());
        category.setRecTime(new Date());
        int categoryNameCont = categoryService.count(new LambdaQueryWrapper<Category>()
                .eq(Category::getCategoryName, category.getCategoryName()));
        if (categoryNameCont > 0) {
            throw new ApiException("类目名称已存在！");
        }
        categoryService.saveCategroy(category);
        return JsonResult.ok();
    }

    /**
     * 更新分类
     */
    @PutMapping
    public JsonResult<String> update(@RequestBody Category category) {
        if (Objects.equals(category.getParentId(), category.getCategoryId())) {
            return JsonResult.fail("分类的上级不能是自己本身");
        }
        Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName, category.getCategoryName())
                .eq(Category::getShopId, category.getShopId()).ne(Category::getCategoryId, category.getCategoryId()));
        if (categoryName != null) {
            throw new MyException("类目名称已存在！");
        }
        Category categoryDB = categoryService.getById(category.getCategoryId());
        // 如果从下线改成正常，则需要判断上级的状态
        if (Objects.equals(categoryDB.getStatus(), 0) && Objects.equals(category.getStatus(), 1) && !Objects.equals(category.getParentId(), 0L)) {
            Category parentCategory = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryId, category.getParentId()));
            if (Objects.isNull(parentCategory) || Objects.equals(parentCategory.getStatus(), 0)) {
                // 修改失败，上级分类不存在或者不为正常状态
                throw new MyException("修改失败，上级分类不存在或者不为正常状态");
            }
        }
        categoryService.updateCategroy(category);
        return JsonResult.ok();
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/{categoryId}")
    public JsonResult<String> delete(@PathVariable("categoryId") Long categoryId) {
        if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId, categoryId)) > 0) {
            return JsonResult.fail("请删除子分类，再删除该分类");
        }
        categoryService.deleteCategroy(categoryId);
        return JsonResult.ok();
    }

    /**
     * 所有的
     */
    @GetMapping("/listCategory")
    public JsonResult<List<Category>> listCategory() {
        return JsonResult.ok(categoryService.list(new LambdaQueryWrapper<Category>()
                .le(Category::getGrade, 2)
                .orderByAsc(Category::getSeq)));
    }

    /**
     * 所有的产品分类
     */
    @GetMapping("/listProdCategory")
    public JsonResult<List<Category>> listProdCategory() {
        List<Category> categories = categoryService.treeSelect(2);
        return JsonResult.ok(categories);
    }


}
